package cn.edu.wfit.service;



import cn.edu.wfit.entity.Role;
import cn.edu.wfit.entity.Users;
import cn.edu.wfit.entity.UsersRole;
import cn.edu.wfit.mapper.UsersMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class AuthorizeService implements UserDetailsService {
    //    @Autowired
//    private UsersMapper mapper;
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private IUsersRoleService iUsersRoleService;
    @Autowired
    private IRoleService iRoleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Users::getName, username);
        Users users = usersMapper.selectOne(queryWrapper);
//        Users users1 = usersMapper.finfusersByName(username);
        if (users == null) {
            throw new UsernameNotFoundException("在即可系统里没有找到该用户");
        }


        UsersRole one = iUsersRoleService.getOne(new LambdaQueryWrapper<UsersRole>().eq(UsersRole::getUsersId, users.getId()));
        Role one1 = iRoleService.getOne(new LambdaQueryWrapper<Role>().eq(Role::getId,  one.getRoleId()));


        return User.withUsername(users.getName()).password(users.getPassword()).roles(one1.getName()).build();
    }


}
